package cn.stylefeng.guns.modular.api.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtils;
import cn.stylefeng.guns.modular.api.entity.Task;
import cn.stylefeng.guns.modular.api.entity.TaskRecord;
import cn.stylefeng.guns.modular.api.mapper.TaskMapper;
import cn.stylefeng.guns.modular.api.mapper.TaskRecordMapper;
import cn.stylefeng.guns.modular.api.model.enums.CommonStatusEnum;
import cn.stylefeng.guns.modular.api.model.enums.TaskTypeEnum;
import cn.stylefeng.guns.modular.api.model.params.TaskParam;
import cn.stylefeng.guns.modular.api.model.params.TaskRecordParam;
import cn.stylefeng.guns.modular.api.model.result.TaskRecordResult;
import cn.stylefeng.guns.modular.api.model.result.TaskResult;
import cn.stylefeng.guns.modular.api.service.TaskRecordService;
import cn.stylefeng.guns.modular.api.service.TaskService;
import cn.stylefeng.guns.modular.api.service.WxPushServiceQcl;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 任务管理 服务实现类
 * </p>
 *
 * @author samwuu
 * @since 2019-10-10
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private TaskRecordService taskRecordService;

    @Autowired
    private TaskRecordMapper taskRecordMapper;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Override
    @Transactional
    public void add(TaskParam param) {
        Task entity = getEntity(param);
        this.save(entity);

        TaskResult taskResult = new TaskResult();
        BeanUtils.copyProperties(entity,taskResult);
        wxPushServiceQcl.pushOneUser(param.getFormId(),taskResult);
    }

    @Override
    public void saveAll(List<Task> tasks) {
        this.saveBatch(tasks);
    }

    @Override
    public void delete(TaskParam param) {
        this.baseMapper.deleteByParam(param);
    }

    @Override
    @Transactional
    public void done(TaskParam param) {

        if (param.getType() != TaskTypeEnum.NORMAL.getCode().longValue()) {

            TaskRecordParam taskRecordParam = new TaskRecordParam();
            taskRecordParam.setType(param.getType().intValue());
            taskRecordParam.setTaskId(param.getTaskId());
            TaskRecordResult taskRecordResult = taskRecordService.findBySpec(taskRecordParam); //把最近的记录拿出来

            BeanUtils.copyProperties(taskRecordResult,taskRecordParam);
            taskRecordParam.setRemark(param.getRemark());
            taskRecordParam.setMedias(param.getMedias());
            taskRecordParam.setStatus(CommonStatusEnum.DONE.getCode());

            TaskRecord taskRecord = new TaskRecord();
            BeanUtils.copyProperties(taskRecordParam,taskRecord);
            taskRecordMapper.updateById(taskRecord);

        } else {
            param.setStatus(CommonStatusEnum.DONE.getCode().toString());
            update(param);
        }

        TaskResult taskResult = this.findBySpec(param);
        wxPushServiceQcl.pushOneUser(param.getFormId(),taskResult);


    }

    @Override
    @Transactional
    public void update(TaskParam param) {

        Task oldEntity = getOldEntity(param);
        Task newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public TaskResult findBySpec(TaskParam param) {
        TaskResult taskResult = new TaskResult();
        Task task = this.baseMapper.selectById(param.getTaskId());
        BeanUtils.copyProperties(task, taskResult);
        if (task.getType() != TaskTypeEnum.NORMAL.getCode().longValue()) {
            TaskRecordParam taskRecordParam = new TaskRecordParam();
            taskRecordParam.setType(task.getType().intValue());
            taskRecordParam.setTaskId(task.getTaskId());
            TaskRecordResult taskRecordResult = taskRecordService.findBySpec(taskRecordParam);
            taskResult.setStatus(taskRecordResult.getStatus().toString());
            return taskResult;
        } else {
            return taskResult;
        }
    }

    @Override
    public Integer unDone(TaskParam param) {

        List<Task> tasks = this.baseMapper.customList(param);
        return tasks.size();
    }

    @Override
    public List<Task> findListBySpec(TaskParam param) {
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(TaskParam param) {
        Page pageContext = getPageContext();
        if (pageContext.getSize() == 0) {
            List datas = this.baseMapper.customList(param);
            return LayuiPageFactory.createDataInfo(datas);
        }
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(TaskParam param) {
        return param.getTaskId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Task getOldEntity(TaskParam param) {
        return this.getById(getKey(param));
    }

    private Task getEntity(TaskParam param) {
        Task entity = new Task();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    public void taskEveryDay() {
        try {

            Date todayDate = DateUtils.getNowDate();
            String todayDateStr = DateUtil.formatDate(todayDate);
            List<Task> taskList = this.baseMapper.selectList(null);
            for (int i = 0; i < taskList.size(); i++) {

                Task task = taskList.get(i);
                Date startDate = task.getCreateTime();
                Long dayDiff = DateUtil.betweenDay(startDate, todayDate, false) + 1L;

                //排除普通任务
                if (task.getType() != TaskTypeEnum.NORMAL.getCode().intValue() &&
                        task.getStatus().equals(CommonStatusEnum.NORMAL.getCode().toString())) {
                    //没结束
                    TaskRecordParam taskRecordParam = new TaskRecordParam();
                    taskRecordParam.setRecord(task.getContent());
                    taskRecordParam.setTaskId(task.getTaskId());
                    taskRecordParam.setPlanId(task.getPlanId());
                    taskRecordParam.setType(task.getType().intValue());

                    if (task.getType().equals(TaskTypeEnum.DAY.getCode().longValue())) {
                        taskRecordParam.setReportDate(todayDateStr);
                        taskRecordParam.setTitle(String.format("日任务-%s", todayDateStr));
                        taskRecordService.add(taskRecordParam);

                    } else if (task.getType().equals(TaskTypeEnum.WEEK.getCode().longValue())) {

                        if (dayDiff % 7 == 0) {
                            Integer num = dayDiff.intValue() / 7 + 1;
                            taskRecordParam.setTitle(String.format("周任务-第%d周", num));
                            taskRecordService.add(taskRecordParam);
                        }
                    } else if (task.getType().equals(TaskTypeEnum.MOUTH.getCode().longValue())) {

                        if (dayDiff % 30 == 0) {
                            Integer num = dayDiff.intValue() / 30 + 1;
                            taskRecordParam.setTitle(String.format("月任务-第%d月", num));
                            taskRecordService.add(taskRecordParam);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
